from utils import platform
from lib.net.index import wlan


class TCP:
    def __init__(self):
        wlan.connect()

    def connect(self, domain, port):
        if platform.is_esp32_series():
            from lib.net.tcp import tcp_esp32
            return tcp_esp32.connect(domain, port)
        if platform.is_raspberry_pico_series():
            from lib.net.tcp import tcp_at
            return tcp_at.connect(domain, port)

    def disconnect(self):
        if platform.is_esp32_series():
            from lib.net.tcp import tcp_esp32
            return tcp_esp32.disconnect()
        if platform.is_raspberry_pico_series():
            from lib.net.tcp import tcp_at
            return tcp_at.disconnect()

    def read(self, param = 100):
        """
        AT 默认每次等待读取串口100ms
        ESP32 为读取的字节数
        """
        if platform.is_esp32_series():
            from lib.net.tcp import tcp_esp32
            return tcp_esp32.read(param)
        if platform.is_raspberry_pico_series():
            from lib.net.tcp import tcp_at
            return tcp_at.read(param)

    def write(self, buf):
        if buf is None:
            return
        if platform.is_esp32_series():
            from lib.net.tcp import tcp_esp32
            return tcp_esp32.write(buf)
        if platform.is_raspberry_pico_series():
            from lib.net.tcp import tcp_at
            return tcp_at.write(buf)

tcp = TCP()

if __name__ == "__main__":
    tcp.connect("creation-hardware.codemao.cn", 3000)
    buf = '{"op": "upload","topic":"Tiot_spneZhyC","name":"dataset","data": "at,1,2,3"}'
    tcp.write(buf)
    recv = tcp.read()
    print(recv)
    tcp.disconnect()